var Koa = require('koa')
var config = require('./wechat/config')
var wechat = require('./wechat/g')
var weixin = require('./wechat/weixin')
var Router = require('koa-router');
var Wechat = require('./wechat/wechat') 

var users = require('./wechat/mongoose') 

var tools = require('./libs/tools')
var bodyParser = require('koa-body-parser');
var db = require('./wechat/db')
var sha1 = require('sha1');
var cors = require('koa-cors');  
var app = new Koa();
var router = new Router();


 
app.use(cors());  
app.use(bodyParser());

 

 
router.get('/GoodsBook', function *(next) {  //物品分类
  var condition = tools.jointCondition(this.query,'WZ_GoodsBook')
 // var data= yield db.dbfind('WZ_GoodsBook')//WZ_GoodsBigCat
 var data= yield db.find(condition)
  this.body = data
});
router.get('/GoodsBigCat', function *(next) {
  var condition = tools.jointCondition(this.query,'WZ_GoodsBigCat')
  var data= yield db.find(condition) //WZ_GoodsBigCat
   
  this.body = data
});

router.get('/GoodsMidCat', function *(next) {
  var condition = tools.jointCondition(this.query,'WZ_GoodsMidCat')
  var data= yield  db.find(condition)  //WZ_GoodsMidCat
  this.body = data
});

router.get('/Sys_Goods', function *(next) {
  var condition = tools.jointCondition(this.query,'WZ_Sys_Goods')
  var data= yield  db.find(condition)  //WZ_Sys_Goods
  this.body = data
});
//fuzzySys_Goods
router.get('/fuzzySys_Goods', function *(next) {
  var condition = tools.jointFuzzyCondition(this.query,'WZ_Sys_Goods')
  var data= yield db.find(condition)  //WZ_Sys_Goods
  this.body = data
});
//Store_Batch
router.get('/Store_Batch', function *(next) {
  var condition = tools.findNCondition(this.query,'WZ_Store_Batch',100)
  var data= yield  db.find(condition)  //WZ_Store_Batch
  this.body = data
});


router.get('/',wechat(config.wechat,weixin.reply));
router.post('/',wechat(config.wechat,weixin.reply));
//app.use(wechat(config.wechat,weixin.reply))
router.get('/jsticket', function *(next) {
  var that = this;
  var wechat =  new Wechat(config.wechat);
  var data =  yield new  Promise(function(resolve, reject) {
      wechat.fecthJsapiTicketToken(function(data){
        resolve(data)
      });
    }) 
  var noncestr = this.query.nonceStr;
  var jsapi_ticket =  data.ticket;
  var timestamp =  parseInt(new Date()/1000);
  var url = this.query.url;
  var str =  ['noncestr='+noncestr,'jsapi_ticket='+jsapi_ticket,'timestamp='+timestamp,'url='+url].sort().join('&');
  var sha = sha1(str);
  this.body = {
    appId:config.wechat.appID,
    timestamp:timestamp,
    nonceStr: noncestr,
    signature: sha,
    jsapi_ticket : jsapi_ticket
  
  }
  

});

router.post('/user', function *(next) {
  var json = this.request.body.params;
  
  var data = yield new Promise(function(resolve,reject){
    users.find(json, function (err, comment) {
      
      resolve(comment)
    })
  })
  //var data = yield config.wechat.getUsers()
  this.body = data
})

router.get('/oauth', function *(next) {
  var that = this;
 var code = this.query.code
  
 if (code){
  var wechat =  new Wechat(config.wechat);
  var data = yield wechat.fecthOAuthAccessToken(code);
  var json = yield wechat.getUserinfo(data);

   //存储用户信息
//先查询数据库
yield new Promise(function(resolve,reject){
  users.find({'openid': json.openid}, function (err, arr) {
     
    if(arr.length==0){
      users.create(json,function(err, comment){
        resolve(comment)
      })
    }else {
      resolve(arr)
    }
  })
})
  
 // yield config.wechat.saveUsers(json)
  this.redirect('http:/122.112.213.124/wxweb?openid='+json.openid);
 // this.body = JSON.stringify(json)
 }else{
  this.body = "NO CODE";
 }
 
});

var redirect_uri = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7f1f5b8289efc363&redirect_uri=http://122.112.213.124:3000/oauth&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
//router.redirect('/wx_login', redirect_uri);
 
router.all('/wx_login', function *() {
  this.redirect(redirect_uri);
  this.status = 301;
});


app.use(router.routes()).use(router.allowedMethods());

app.listen(3000)